package com.aigc.txt2img.controller.api;

import com.aigc.txt2img.config.PagerConfig;
import com.aigc.txt2img.entity.User;
import com.aigc.txt2img.exception.ExceptionEnum;
import com.aigc.txt2img.service.UserService;
import com.aigc.txt2img.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/java_api/user")
public class UserController {


    @Autowired
    UserService userService;
    /**
     * http://localhost:8080/api/user/add
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseUtil addUser(@Validated User user) {
        int ret = userService.addUser(user);
        if (ret > 0) {
            System.out.println("user:" + user);
            Map<String, Integer> data = new HashMap<>();
            data.put("id", user.getId());
            return ResponseUtil.success(data);
        }
        return ResponseUtil.error(ExceptionEnum.SERVER_BUSY);
    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public ResponseUtil getByID(int id) {
        return ResponseUtil.success(userService.getByID(id));
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResponseUtil updateUser(@Validated User user) {
        int ret =  userService.updateUser(user);
        if (ret > 0) {
            return ResponseUtil.success();
        }
        return ResponseUtil.error(ExceptionEnum.SERVER_BUSY);
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ResponseUtil deleteUser(int id) {
        int ret =  userService.deleteUser(id);
        if (ret > 0) {
            return ResponseUtil.success();
        }
        return ResponseUtil.error(ExceptionEnum.SERVER_BUSY);
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseUtil getList(@RequestParam("pg") int pg, @RequestParam("size") int size ) {
        System.out.println("in list 333");
        if (pg < PagerConfig.PAGE_MIN) {
            pg = PagerConfig.PAGE_MIN;
        }
        if (size < PagerConfig.PAGE_SIZE_MIN || size > PagerConfig.PAGE_SIZE_MAX) {
            size = PagerConfig.PAGE_SIZE_MAX;
        }
        int offset = (pg-1)*size;
        System.out.println("offset:" + offset + " size:" + size);
        log.debug("this is debug");
        log.info("this is info");
        List<User> ret =  userService.getList(offset, size);
        return ResponseUtil.success(ret);
    }

}